<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <!-- 接收TodoHeader传过来的任务名 -->
    <TodoHeader :list="changeTaskList" @addTask="addTaskHandler"></TodoHeader>
    <!-- 传数组数据给TodoMain    接收TodoMain传来的数据-->
    <TodoMain :list="changeTaskList" @delTask="delTaskHandler"></TodoMain>
    <TodoFooter :list="changeTaskList" @changeTask="changeTaskHandler" @clearYes="clearYesHandler"></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todolist')||'[]') ,
      isOk:'all'
    };
  },
  methods: {
    // 添加任务
    addTaskHandler(taskVal) {
      let id =
        this.list.length == 0 ? 100 : this.list[this.list.length - 1].id + 1;
      // 添加到数组中
      this.list.push({
        id,
        name: taskVal,
        isDone: false,
      });
    },
    // 删除任务
    delTaskHandler(id) {
      this.list.splice(
        this.list.findIndex((item) => item.id == id),
        1
      );
    },
    changeTaskHandler(isOk) {
      this.isOk = isOk
    },
    clearYesHandler(){
     this.list = this.list.filter(item => !item.isDone)
    }
  },
  computed:{
    changeTaskList(){
      if ( this.isOk == "yes") {
        return this.list.filter((item) => item.isDone);
      } else if ( this.isOk == "no") {
        return this.list.filter((item) => !item.isDone);
      }else{
        return this.list
      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler(){
        localStorage.setItem('todolist',JSON.stringify(this.list))
      }
    }
  }
};
</script>